package com.hzxy.yiyid.web.module.service.impl;

import com.hzxy.yiyid.web.module.controller.vo.NearbyOrganizationRequestVO;
import com.hzxy.yiyid.web.module.service.OrganizationService;
import com.hzxy.yiyid.web.tool.ip.IpTool;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.*;

/**
 * @ClassName OrganizationServiceImpl
 * @Description 医保定点机构相关
 * @Author RAICOM2023
 * @Date 2023/3/6 8:58
 * @Version 1.0
 **/
@Service(value = "organizationService")
@Transactional
public class OrganizationServiceImpl implements OrganizationService {

    private static final Logger logger = LoggerFactory.getLogger(OrganizationServiceImpl.class);

    @Autowired
    private EntityManager em;

    /*
     * @Author RAICOM2023
     * @Description //获得附近的医疗/医保机构
     * @Date 8:57 2023/3/6
     * @Param [nearbyOrganizationRequestVO, request]
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     **/
    @Override
    public List<Map<String, Object>> listNearbyOrganization(NearbyOrganizationRequestVO nearbyOrganizationRequestVO
            , HttpServletRequest request) throws Exception {
        List<String> regionList = getRegion(request);
        List<Map<String, Object>> assignOrganizationMapList = new ArrayList<>();
        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append("select * from assign_organization where 1 = 1 ");
        sqlStr.append("and type = '" + nearbyOrganizationRequestVO.getType() + "' ");

       if(StringUtils.isNotBlank(regionList.get(2))){
            sqlStr.append("and county like '%" + regionList.get(2) + "%'");
       }else if(StringUtils.isNotBlank(regionList.get(1))){
            sqlStr.append("and city like '%" + regionList.get(1) + "%'");
       }else{
          return assignOrganizationMapList;
       }
      //sqlStr.append(" and dz like '%西湖区%'");

       Integer startIndex = (nearbyOrganizationRequestVO.getPageNo() - 1) * nearbyOrganizationRequestVO.getPageSize();
        //plgresql分页SQL
        /*sqlStr.append(
                " order by id asc limit '" + nearbyOrganizationRequestVO.getPageSize() + "' "
                        + "offset '"
                        + startIndex + "'");*/
        //MySQL分页SQL
        sqlStr.append(
                " order by id asc limit " + nearbyOrganizationRequestVO.getPageSize() + " offset " + startIndex + "");
        String sql = sqlStr.toString();
        logger.info("附件定点医疗医药机构查询SQL：" + sql);
        Query query = em.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<?> rows = query.getResultList();
        if(CollectionUtils.isEmpty(rows)){
            return assignOrganizationMapList;
        }else{
            for(Object obj : rows){
                Map<String, String> hashMap = new LinkedHashMap<>();
                Map<Object, Object> map = (Map)obj;
                for (Object key : map.keySet()) {
                    if (null == map.get(key) || "".equals(map.get(key).toString())) {
                        hashMap.put(key.toString().toUpperCase(), null);
                    } else {
                        hashMap.put(key.toString().toUpperCase(), map.get(key).toString());
                    }
                }
                Map<String, Object>  assignOrganizationMap = new HashMap<>();
                assignOrganizationMap.put("id", hashMap.get("ID"));
                assignOrganizationMap.put("ffrq", hashMap.get("FFRQ"));
                assignOrganizationMap.put("jgmc", hashMap.get("JGMC"));
                assignOrganizationMap.put("dz", hashMap.get("DZ"));
                assignOrganizationMap.put("dj", hashMap.get("DJ"));
                assignOrganizationMap.put("ddlb", hashMap.get("DDLB"));
                assignOrganizationMap.put("jgbm", hashMap.get("JGBM"));
                assignOrganizationMap.put("type", hashMap.get("TYPE"));
                assignOrganizationMap.put("province", hashMap.get("PROVINCE"));
                assignOrganizationMap.put("city", hashMap.get("CITY"));
                assignOrganizationMap.put("county", hashMap.get("COUNTY"));
                assignOrganizationMap.put("town", hashMap.get("TOWN"));
                assignOrganizationMap.put("detail", hashMap.get("DETAIL"));
                assignOrganizationMapList.add(assignOrganizationMap);
            }
        }
        em.close();
        return assignOrganizationMapList;
    }

    /*
     * @Author RAICOM2023
     * @Description //获得附近的医疗/医保机构--总数
     * @Date 8:58 2023/3/6
     * @Param [nearbyOrganizationRequestVO]
     * @return long
     **/
    @Override
    public long findNearbyOrganizationTotal(NearbyOrganizationRequestVO nearbyOrganizationRequestVO, HttpServletRequest request) throws Exception {
        List<String> regionList = getRegion(request);
        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append("select count(*) from assign_organization where 1 = 1 ");
        sqlStr.append("and type = '" + nearbyOrganizationRequestVO.getType() + "' ");
        if(StringUtils.isNotBlank(regionList.get(2))){
            sqlStr.append("and county like '%" + regionList.get(2) + "%'");
        }else if(StringUtils.isNotBlank(regionList.get(1))){
            sqlStr.append("and city like '%" + regionList.get(1) + "%'");
        }else{
            return 0;
        }
        //sqlStr.append("and city like '%杭州市%' and dz like '%西湖区%'");
        String sql = sqlStr.toString();
        Query query = em.createNativeQuery(sql);
        Object o = query.getSingleResult();
        em.close();
        if(o == null){
            return 0L;
        }else{
            BigInteger big = (BigInteger) o;
            return big.longValue();
        }
    }

    @Override
    public List<Map<String, Object>> listNearbyFeverClinic(NearbyOrganizationRequestVO nearbyOrganizationRequestVO, HttpServletRequest request) throws Exception {
        List<String> regionList = getRegion(request);
        List<Map<String, Object>> feverClinicMapList = new ArrayList<>();
        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append("select * from fever_clinic where 1 = 1 ");

        if(StringUtils.isNotBlank(regionList.get(2))){
            sqlStr.append("and county like '%" + regionList.get(2) + "%'");
        }else if(StringUtils.isNotBlank(regionList.get(1))){
            sqlStr.append("and city like '%" + regionList.get(1) + "%'");
        }else{
            return feverClinicMapList;
        }

        Integer startIndex = (nearbyOrganizationRequestVO.getPageNo() - 1) * nearbyOrganizationRequestVO.getPageSize();
        sqlStr.append(
                "order by id asc limit '" + nearbyOrganizationRequestVO.getPageSize() + "' "
                        + "offset '"
                        + startIndex + "'");
        String sql = sqlStr.toString();
        logger.info("查询附近定点机构SQL：" + sql);
        Query query = em.createNativeQuery(sql);
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        List<?> rows = query.getResultList();
        if(CollectionUtils.isEmpty(rows)){
            return feverClinicMapList;
        }else{
            for(Object obj : rows){
                Map<String, String> hashMap = new LinkedHashMap<>();
                Map<Object, Object> map = (Map)obj;
                for (Object key : map.keySet()) {
                    if (null == map.get(key) || "".equals(map.get(key).toString())) {
                        hashMap.put(key.toString().toUpperCase(), null);
                    } else {
                        hashMap.put(key.toString().toUpperCase(), map.get(key).toString());
                    }
                }
                Map<String, Object>  feverClinicMap = new HashMap<>();
                feverClinicMap.put("id", hashMap.get("ID"));
                feverClinicMap.put("jgmc", hashMap.get("JGMC"));
                feverClinicMap.put("dz", hashMap.get("DZ"));
                feverClinicMap.put("province", hashMap.get("PROVINCE"));
                feverClinicMap.put("city", hashMap.get("CITY"));
                feverClinicMap.put("county", hashMap.get("COUNTY"));
                feverClinicMap.put("town", hashMap.get("TOWN"));
                feverClinicMap.put("detail", hashMap.get("DETAIL"));
                feverClinicMapList.add(feverClinicMap);
            }
        }
        em.close();
        return feverClinicMapList;
    }

    @Override
    public long findNearbyFeverClinicTotal(NearbyOrganizationRequestVO nearbyOrganizationRequestVO, HttpServletRequest request) throws Exception {
        List<String> regionList = getRegion(request);
        StringBuilder sqlStr = new StringBuilder();
        sqlStr.append("select count(*) from fever_clinic where 1 = 1 ");
        if(StringUtils.isNotBlank(regionList.get(2))){
            sqlStr.append("and county like '%" + regionList.get(2) + "%'");
        }else if(StringUtils.isNotBlank(regionList.get(1))){
            sqlStr.append("and city like '%" + regionList.get(1) + "%'");
        }else{
            return 0;
        }
        String sql = sqlStr.toString();
        Query query = em.createNativeQuery(sql);
        Object o = query.getSingleResult();
        em.close();
        if(o == null){
            return 0L;
        }else{
            BigInteger big = (BigInteger) o;
            return big.longValue();
        }
    }

    /*
     * @Author RAICOM2023
     * @Description //获取访客地址
     * @Date 11:38 2023/3/6
     * @Param [request]
     * @return java.util.List<java.lang.String>
     **/
    private List<String> getRegion(HttpServletRequest request){
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        String ip = ipAddress.split(",")[0];

       // String ip = IpTool.getAddress(IpTool.getIp());
        System.out.println(ip);

        logger.info("访客的ip地址："+ip);
//        logger.info("暂时固定一个西湖区ip："+"115.193.186.66");
        List<String> regionList = new ArrayList<String>();
        boolean baiduSuccessFlag = true;
        // 先不要用百度的接口
        //baiduSuccessFlag = false;
        /*try{
            regionList = BaiduIpRegion.getRegion(ip);
        }catch(Exception e){
            baiduSuccessFlag = false;
            logger.error("调用百度接口根据ip获取地址信息异常",e);
        }*/

        logger.info("ip--region"+IpTool.getCityInfo(ip));
        regionList = IpTool.getCityInfo(ip);
        for(String s : regionList)
            System.out.println(s);

        return regionList;
    }
}
